<template>
  <div>
    <van-nav-bar
      title="更新昵称"
      left-text="取消"
      right-text="保存"
      @click-left="$emit('close')"
      @click-right="onClickRight"
    />
    <van-field
      v-model.trim="message"
      type="textarea"
      maxlength="7"
      placeholder="请输入新的昵称"
      show-word-limit
    />
  </div>
</template>

<script>
import { PatchUserProfile } from '@/api/user.js'
import { Toast } from 'vant'
export default {
  data () {
    return {
      message: ''
    }
  },
  props: {
    value: {
      type: String,
      required: true
    }
  },
  created () {
    this.message = this.value
  },

  methods: {
    async onClickRight () {
      if (this.message === '' || this.message === this.value) return Toast.fail('昵称未更改或为空')
      Toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true
      })
      try {
        const res = await PatchUserProfile({
          name: this.message
        })
        console.log(res)
        Toast.success('更新成功！')
        this.$emit('input', this.message)
        this.$emit('close')
      } catch (err) {
        if (err.response && err.response.status === 409) return Toast.fail('昵称已存在！')
        Toast.fail('更新失败！')
      }
    }
  }
}
</script>

<style scoped lang='less'>

</style>
